<script setup>
import { ref, getCurrentInstance, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";
import config from "@/config/index.js";

const { proxy } = getCurrentInstance();

// 表格数据
const tableData = ref([]);

// 分页相关状态
const currentPage = ref(1);
const pageSize = ref(10);

// 分页计算
const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return tableData.value.slice(start, end);
});

// 样本列表数据
const sampleList = ref([]);

// 下拉框选中的样本
const selectedSample = ref(null);

// 表单数据
const formData = ref({
  id: "",
  sampleId: "",
  spatialCoordinates: "",
  file: null, // 上传的文件
  imagePath: "", // 图片路径
  annotationType: "",
  description: "",
  createdBy: "",
  updatedBy: "",
});

// 处理文件选择
const handleFileChange = (uploadFile) => {
  formData.value.file = uploadFile.raw;
};

// 上传文件
const uploadFile = async () => {
  if (!formData.value.file) {
    ElMessage.warning("请先选择文件");
    return;
  }

  const uploadForm = new FormData();
  uploadForm.append("file", formData.value.file);

  try {
    const uploadRes = await axios.post("/api/annotations/upload", uploadForm, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    });

    if (uploadRes.data?.success) {
        formData.value.imagePath =
        "\\\\" + uploadRes.data.data.filePath.replace(/\\/g, "\\\\"); // 提取 filePath 并赋值给表单
      ElMessage.success("图片上传成功");
    } else {
      throw new Error(uploadRes.data?.message || "图片上传失败");
    }
  } catch (error) {
    console.error("图片上传失败:", error);
    ElMessage.error("图片上传失败，请重试");
  }
};

// 弹框相关状态
const dialogVisible = ref(false);
const dialogTitle = ref("");
const formRef = ref(null);

// 表单验证规则
const formRules = ref({
  sampleId: [{ required: true, message: "请输入样本ID", trigger: "blur" }],
  spatialCoordinates: [
    { required: true, message: "请输入空间坐标", trigger: "blur" },
  ],
  imagePath: [{ required: true, message: "请输入图片路径", trigger: "blur" }],
  annotationType: [
    { required: true, message: "请输入标注类型", trigger: "blur" },
  ],
  description: [{ required: true, message: "请输入描述信息", trigger: "blur" }],
});

// 获取样本列表
const getSampleList = async () => {
  try {
    const data = await proxy.$api.getSampleList();
    sampleList.value = data; // 将获取到的样本数据赋值给 sampleList
  } catch (error) {
    ElMessage.error("获取样本列表失败：" + error.message);
  }
};

// 获取标注数据
const getAnnotationList = async (sampleId = null) => {
  try {
    const params = sampleId ? { sampleId } : {};
    const data = await proxy.$api.getAnnotationList(params);
    tableData.value = data;
  } catch (error) {
    ElMessage.error("获取标注数据失败：" + error.message);
  }
};

// 处理下拉框选中变化
const handleSampleChange = (value) => {
  console.log("选中的样本ID:", value);
  getAnnotationList(value);
  // 可以根据选中的样本ID执行其他逻辑
};

// 分页变化时触发
const handlePageChange = (page) => {
  currentPage.value = page;
};

const handlePageSizeChange = (size) => {
  pageSize.value = size;
};

// 新增数据
const handleAdd = () => {
  dialogTitle.value = "新增标注";
  formData.value = {
    id: "",
    sampleId: "",
    spatialCoordinates: "",
    imagePath: "",
    annotationType: "",
    description: "",
    createdBy: "",
    updatedBy: "",
    file: null,
  };
  dialogVisible.value = true;
};

// 编辑数据
const handleEdit = (row) => {
  dialogTitle.value = "编辑标注";
  formData.value = { ...row, file: null };
  dialogVisible.value = true;
};

// 删除数据
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认要删除 ID 为 "${row.id}" 的标注数据吗？`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        await proxy.$api.deleteAnnotation(row.id);
        ElMessage.success("删除成功");
        getAnnotationList();
      } catch (error) {
        ElMessage.error("删除失败: " + error.message);
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate();

    // 确保 sampleId 是数字类型
    formData.value.sampleId = Number(formData.value.sampleId);

    if (formData.value.id) {
      // 编辑
      await proxy.$api.updateAnnotation(formData.value);
      ElMessage.success("更新成功");
    } else {
      // 新增
      await proxy.$api.addAnnotation(formData.value);
      ElMessage.success("新增成功");
    }

    dialogVisible.value = false;
    getAnnotationList();
  } catch (error) {
    if (!error.message) {
      // 验证失败不显示错误消息
      return;
    }
    ElMessage.error("操作失败: " + error.message);
  }
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

// 页面加载时获取数据
onMounted(() => {
  getSampleList(); // 获取样本列表
  getAnnotationList(); // 获取标注数据
});
</script>

<template>
  <div class="app-container">
    <!-- 操作栏 -->
    <div class="mb-4">
      <!-- 下拉列表框 -->
      <el-select
        v-model="selectedSample"
        placeholder="请选择样本"
        style="width: 200px; margin-right: 10px"
        @change="handleSampleChange"
      >
        <el-option
          v-for="sample in sampleList"
          :key="sample.id"
          :label="sample.name"
          :value="sample.id"
        />
      </el-select>

      <!-- 新增按钮 -->
      <el-button type="primary" @click="handleAdd">
        <el-icon><plus /></el-icon>
        新增
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table :data="currentPageData" style="width: 100%" border stripe>
      <!-- ID 列 -->
      <el-table-column prop="id" label="ID" width="80" align="center" />

      <!-- 样本ID列 -->
      <el-table-column
        prop="sampleId"
        label="样本ID"
        align="center"
        width="120"
      />

      <!-- 空间坐标列 -->
      <el-table-column
        prop="spatialCoordinates"
        label="空间坐标"
        align="center"
        min-width="200"
        show-overflow-tooltip
      />

      <!-- 图片展示列 -->
      <el-table-column label="图片展示" align="center" min-width="200">
        <template #default="scope">
          <el-image
            :src="config.imagePath +`${scope.row.imagePath
              .replace(/\\/g, '/')
              .replace(/^\//, '')}`"
            fit="cover"
            style="
              width: 100px;
              height: 100px;
              border-radius: 8px;
              object-fit: cover;
            "
            lazy
          >
            <template #error>
              <div
                style="
                  width: 100px;
                  height: 100px;
                  background: #f2f2f2;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  border-radius: 8px;
                "
              >
                加载失败
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>

      <!-- 标注类型列 -->
      <el-table-column
        prop="annotationType"
        label="标注类型"
        align="center"
        width="120"
      />

      <!-- 描述列 -->
      <el-table-column
        prop="description"
        label="描述"
        align="center"
        min-width="180"
        show-overflow-tooltip
      />

      <!-- 操作列 -->
      <el-table-column fixed="right" label="操作" width="180" align="center">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      class="pagination"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50]"
      layout="total, sizes, prev, pager, next"
      :total="tableData.length"
      @current-change="handlePageChange"
      @size-change="handlePageSizeChange"
    />

    <!-- 新增/编辑弹框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="50%"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        label-position="right"
      >
        <!-- 样本ID下拉框 -->
        <el-form-item label="样本" prop="sampleId">
          <el-select
            v-model="formData.sampleId"
            placeholder="请选择样本"
            style="width: 100%"
          >
            <el-option
              v-for="sample in sampleList"
              :key="sample.id"
              :label="sample.name"
              :value="sample.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="空间坐标" prop="spatialCoordinates">
          <el-input
            v-model="formData.spatialCoordinates"
            placeholder="请输入空间坐标"
          />
        </el-form-item>

        <el-form-item label="图片上传" prop="imagePath">
          <div style="display: flex; align-items: center; gap: 10px;">
            <!-- 点击上传按钮 -->
            <el-upload
              action="#"
              :auto-upload="false"
              :show-file-list="false"
              :on-change="handleFileChange"
              accept="image/*"
            >
              <el-button type="primary">选择文件</el-button>
            </el-upload>

            <!-- 显示文件名 -->
            <span v-if="formData.file" style="flex: 1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
              已选文件：{{ formData.file.name }}
            </span>

            <!-- 上传按钮 -->
            <el-button
              type="success"
              @click="uploadFile"
              :disabled="!formData.file"
            >
              上传
            </el-button>
          </div>

          <!-- 图片预览 -->
          <div v-if="formData.imagePath" style="margin-top: 10px;">
            <el-image
            :src="config.imagePath +`${formData.imagePath
              .replace(/\\/g, '/')
              .replace(/^\//, '')}`"
              style="width: 100px; height: 100px; border-radius: 8px; object-fit: cover;"
            />
          </div>
        </el-form-item>

        <el-form-item label="标注类型" prop="annotationType">
          <el-input
            v-model="formData.annotationType"
            placeholder="请输入标注类型"
          />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入描述信息"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">
.app-container {
  padding: 20px;
}

.mb-4 {
  margin-bottom: 1rem;
}

.el-table {
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 22px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
